const express = require("express");
const { Setting } = require("../../models");
const router = express.Router();
const { NotFoundError } = require("../../utils/errors");
const { success, failure } = require("../../utils/responses");

/**
 * 获取分类
 * GET /admin/settings
 */
router.get("", async function (req, res) {
  try {
    const setting = await getSetting(req);
    success(res, "Get setting successfully", { setting });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新系统设置
 * PUT /admin/settings
 */
router.put("/", async function (req, res) {
  try {
    const setting = await getSetting(req);
    await setting.update(filterBody(req.body));
    success(res, "Update setting successfully", { setting });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 公共方法： 过滤请求体
 */
function filterBody(body) {
  const { name, icp, copyright } = body;
  return {
    name,
    icp,
    copyright,
  };
}

/**
 * 公共方法： 查询当前系统设置
 */
async function getSetting(req) {
  const setting = await Setting.findOne();
  if (!setting) {
    throw new NotFoundError(`ID: ${id}的系统设置未找到`);
  }
  return setting;
}

module.exports = router;
